<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-change="changeFile"
      :limit="1"
      :before-upload="beforeUpload"
      :class="{disabled : fileComputed}"
      :http-request="upload"
      :file-list="fileList"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="showPercentage" style="width:180px" :percentage="percentage" />
    <el-dialog title="头像预览" :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDL2WxNjxxkIciaDdqobqshIet58zd5JI4',
  SecretKey: 'e4H1bzAC3lLm35zlOtwvoZClQClBWfcp'
})
export default {
  data() {
    return {
      fileList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      fileUid: '',
      percentage: 0,
      showPercentage: false
    }
  },
  computed: {
    fileComputed() {
      return this.fileList.length === 1
    }
  },
  methods: {
    handleRemove(file, fileList) {
      // console.log(file, fileList)
      this.fileList = fileList
    },
    changeFile(file, fileList) {
      // console.log(file, fileList)
      this.fileList = fileList.map(item => item)
      // if (!fileList[0]) {
      //   this.fileList.push(file)
      //   return
      // }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    beforeUpload(file) {
      // console.log(file)
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      // const a = types.find(item => {
      //   console.log(item)
      //   return item === file.type
      // })
      // console.log(a)
      if (!types.find(item => item === file.type)) {
        this.$message.error('上传图片只能是 JPG、GIF、BMP、PNG 格式!')
        return false
      }
      const maxSize = 5 * 1024 * 1024
      if (maxSize < file.size) {
        this.$message.error('图片大小最大不能超过5M')
        return false
      }
      this.fileUid = file.uid
      return true
    },
    upload(params) {
      if (params.file) {
        cos.putObject({
          Bucket: 'jaynb-1315677734', /* 填入您自己的存储桶，必须字段 */
          Region: 'ap-nanjing', /* 存储桶所在地域，例如ap-beijing，必须字段 */
          Key: params.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
          Body: params.file, /* 必须，上传文件对象，可以是input[type="file"]标签选择本地文件后得到的file对象 */
          onProgress: progressData => {
            this.showPercentage = true
            this.percentage = progressData.percent * 100
            // console.log(progressData)
            // console.log(JSON.stringify(progressData))
          }
        }, (err, data) => {
          // console.log(err || data)
          if (!err && data.statusCode === 200) {
            this.showPercentage = false
            this.percentage = 0
            this.fileList = this.fileList.map(item => {
              if (item.uid === this.fileUid) {
                const url = `http://${data.Location}`
                return { url: url, upload: true }
              }
              return item
            })
          }
        })
      }
    }
  }
}
</script>

<style>
.disabled .el-upload--picture-card {
  display: none
}
</style>
